package site.xuxingcan.httpinputmethod;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.inputmethodservice.InputMethodService;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

public class WifiInputMethod extends InputMethodService {

    private boolean mIsEditing = false;
    private TextView tvAddress;
    private BroadcastReceiver textBroadcastReceiver;
    public static final String TEXT_ACTION = "TEXT_ACTION";
    public static final String TEXT = "text";
    private WifiManager mWifiManager;

    public boolean isEditing() {
        return mIsEditing;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private View mContent;

    @Override
    public View onCreateInputView() {
        mContent = LayoutInflater.from(this).inflate(R.layout.wifi_input_method_view, null);
        tvAddress = (TextView) mContent.findViewById(R.id.tvIP);
        return mContent;
    }

    private void changeInputMethod() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showInputMethodPicker();
    }

    public static String getWifiIp(WifiManager mWifiManager) {
        String string_ip = "";
        int code_ip = mWifiManager.getConnectionInfo().getIpAddress();
        if (code_ip != 0) {
            string_ip = (code_ip & 0xFF) + "." +
                    ((code_ip >> 8) & 0xFF) + "." +
                    ((code_ip >> 16) & 0xFF) + "." +
                    ((code_ip >> 24) & 0xFF);
        }
        return string_ip;
    }

    @Override
    public void onStartInputView(EditorInfo info, boolean restarting) {
        super.onStartInputView(info, restarting);
        mIsEditing = true;
        acquireLock();
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()) {
            String address = getWifiIp(mWifiManager);
            if (TextUtils.isEmpty(address)) {
                tvAddress.setText("获取IP地址失败");
            } else {
                tvAddress.setText(address + ":" + MyApplication.HTTP_PORT);
            }
        } else {
            tvAddress.setText("请链接WIFI后使用");
        }

        String text = getText();
        makeToast("onStartInputView: text--" + text);
        textBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null && intent.getStringExtra(TEXT) != null) {
//                    InputConnection conn = getCurrentInputConnection();
//                    conn.commitText(intent.getStringExtra(TEXT), 0);
                    setText(intent.getStringExtra(TEXT));
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(TEXT_ACTION);
        registerReceiver(textBroadcastReceiver, filter);
    }

    private PowerManager.WakeLock mWakeLock;
    public static final String TAG_LOCK = "InputMethod";

    synchronized void acquireLock() {
        if (mWakeLock != null) {
            return;
        }
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG_LOCK);
        mWakeLock.acquire();
    }

    synchronized void releaseWakeLock() {
        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    public String getText() {
        String text = "";
        try {
            InputConnection conn = getCurrentInputConnection();
            ExtractedTextRequest req = new ExtractedTextRequest();
            req.hintMaxChars = 1000000;
            req.hintMaxLines = 10000;
            req.flags = 0;
            req.token = 1;
            text = conn.getExtractedText(req, 0).text.toString();
        } catch (Throwable t) {
        }
        return text;
    }

    public boolean setText(String text) {
        // FIXME: need feedback if the input was lost
        InputConnection conn = getCurrentInputConnection();
        if (conn == null) {
            return false;
        }

        conn.beginBatchEdit();
        // FIXME: hack
        conn.deleteSurroundingText(100000, 100000);
        conn.commitText(text, text.length());
        conn.endBatchEdit();
        return true;
    }

    void makeToast(String msg) {
//        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onFinishInputView(boolean finishingInput) {
        super.onFinishInputView(finishingInput);
        mIsEditing = false;
        releaseWakeLock();
        makeToast("onFinishInputView" + finishingInput);
        if (textBroadcastReceiver != null) {
            unregisterReceiver(textBroadcastReceiver);
        }
    }
}
